import { useState } from "react";
import { View, Text } from "@tarojs/components";
import Taro, { eventCenter } from "@tarojs/taro";
import { Popup, Checkbox, Button, Image } from "@nutui/nutui-react-taro";
import "./index.less";
import logoImage from "../../assets/logo.jpeg";
import AuthUtil from "../../utils/api/auth";
import UserApi from "../../utils/api/user";

const LoginPopupProvider = () => {
  const [visible, setVisible] = useState(false);
  const [isAgreed, setIsAgreed] = useState(false);
  const [tips, setTips] = useState(false);

  eventCenter.on("showLogin", (status: boolean) => {
    setVisible(status);
  });

  const hideLogin = () => {
    setVisible(false);
  };

  //   get user info
  const fetchUserInfo = async () => {
    try {
      const data: any = await UserApi.getCurrentUserInfo();
      // Store updated user info
      if (data) {
        Taro.setStorageSync("userInfo", {
          ...data,
          nickName: data.nickName,
          avatar: data.avatar,
        });
        Taro.showToast({
          title: "登录成功",
          icon: "success",
        });
        // 登录成功后隐藏 loading 提示
        Taro.hideLoading();
        setVisible(false);

        eventCenter.trigger("updateUserInfo", data);
      }
    } catch (error) {
      console.error("获取用户信息失败", error);
    }
  };

  const requestLogin = async (e) => {
    try {
      // 显示登录中的 loading 提示
      Taro.showLoading({
        title: "登录中...",
      });
      if (e.detail.errMsg === "getPhoneNumber:ok") {
        const { code: phoneCode } = e.detail;
        Taro.login({
          success: function (res) {
            AuthUtil.login({ code: res.code, phoneCode }).then((res: any) => {
              console.log(res, "res====");
              if (!res.token) {
                Taro.showToast({
                  title: "登录失败,请重新尝试",
                  icon: "none",
                });

                // 登录失败也隐藏 loading 提示
                Taro.hideLoading();
              } else {
                Taro.setStorageSync("token", res?.token);
                fetchUserInfo();
              }
            });
          },
          fail: function (res) {
            Taro.showToast({
              title: "登录失败,请重新尝试",
              icon: "none",
            });
            console.error("登录失败", res);
            // 登录失败也隐藏 loading 提示
            Taro.hideLoading();
          },
        });
      } else {
        // 登录失败也隐藏 loading 提示
        Taro.hideLoading();
      }
    } catch (error) {
      console.error("登录失败", error);
      // 出现异常时也隐藏 loading 提示
      Taro.hideLoading();
      Taro.showToast({
        title: "登录异常",
        icon: "none",
      });
    }
  };

  // login event
  const handleLogin = (e) => {
    if (isAgreed) {
      requestLogin(e);
    } else {
      setTips(true);
      setTimeout(() => {
        setTips(false);
      }, 1000);
      Taro.showToast({ title: "请先同意隐私条款", icon: "none" });
    }
  };

  //   user agreement

  const handleNavigate = () => {
    Taro.navigateTo({
      url: "/pages/role/index",
    });
  };

  return (
    <View className="popup-box">
      <Popup
        className="popup-container"
        visible={visible}
        position="bottom"
        onClose={hideLogin}
      >
        <View className="login-popup">
          <View className="header">
            <Image
              src={logoImage}
              mode="scaleToFill"
              width="80"
              height="80"
              radius="50%"
            />
            <Text style={{ marginLeft: "20px" }} className="title">
              欢迎使用二手车交易开票网签平台
            </Text>
          </View>

          <View className="login-view">
            {/* 登录按钮 */}
            {isAgreed ? (
              <Button
                block
                className="login-btn"
                type="success"
                openType="getPhoneNumber"
                onGetPhoneNumber={handleLogin}
              >
                手机号码登录
              </Button>
            ) : (
              <Button
                block
                className="login-btn"
                type="success"
                onClick={handleLogin}
              >
                手机号码登录
              </Button>
            )}

            {/* 跳过登录 */}
            <Button
              block
              type="primary"
              fill="outline"
              className="skip-btn"
              onClick={hideLogin}
            >
              暂时跳过
            </Button>
          </View>

          {/* 隐私条款 */}
          <View className={`privacy ${tips ? "shake-horizontal" : ""}`}>
            <Checkbox
              className="test"
              label="请阅读并同意"
              checked={isAgreed}
              onChange={(val) => setIsAgreed(val)}
            />
            <Text style={{ color: "skyblue" }} onClick={handleNavigate}>
              《隐私条款》
            </Text>
          </View>
        </View>
      </Popup>
    </View>
  );
};

export default LoginPopupProvider;
